var express = require("express");
var User = require("../models/user");
var md5 = require("blueimp-md5");
var router = express.Router();

//获取用户列表
router.get("/users", function (req, res) {
    const body = req.query;
    const size = parseInt(body.pagesize);
    const num = (parseInt(body.pagenum) - 1) * size;
    // console.log(body);
    var total = 0;
    User.find({
            $and: [{
                    name: {
                        $regex: body.name
                    }
                },
                {
                    gender: {
                        $regex: body.gender
                    }
                },
                {
                    rank: {
                        $regex: body.rank
                    }
                }
            ]
        })
        .count()
        .then(num => {
            total = num;
        });
    User.find({
            $and: [{
                    name: {
                        $regex: body.name
                    }
                },
                {
                    gender: {
                        $regex: body.gender
                    }
                },
                {
                    rank: {
                        $regex: body.rank
                    }
                }
            ]
        })
        .skip(num)
        .limit(size)
        .then(user => {
            res.json({
                status: 201,
                user: user,
                total: total
            });
        })
        .catch(err =>
            res.json({
                status: 500,
                msg: "查询失败",
                err: err.message
            })
        );
});
//根据id查询信息
router.get("/user", function (req, res) {
    const body = req.query;
    // console.log(body[0]);
    User.find({
        _id: body[0]
    }).then(user => {
        res.json({
            status: 201,
            user: user
        });
    });
});
//根据id删除
router.delete("/user", function (req, res) {
    const body = req.body;
    // console.log(body.id);
    User.remove({
        _id: body.id
    }).then(() => {
        res.json({
            status: 201
        });
    });
});
//根据id修改信息
router.put("/user", function (req, res) {
    const body = req.body;
    // console.log(body);
    User.updateOne({
        _id: body._id
    }, {
        name: body.name,
        rank: body.rank,
        password: md5(body.password),
        gender: body.gender,
        changeTime: body.changeTime
    }).then(() => {
        res.json({
            status: 201
        });
    });
});
//增加用户
router.post("/addUser", function (req, res) {
    const body = req.body;
    User.create({
            name: body.name,
            password: md5(body.password),
            gender: body.gender,
            rank: body.rank
        })
        .then(user => {
            res.json({
                status: 201,
                user: user
            });
        })
        .catch(err =>
            res.json({
                status: 500,
                msg: "添加失败"
            })
        );
});
//处理剩余的
router.use((err, req, res, next) => {
    //接受 next（err）
    // const err_log = `
    //   错误名：${err.name}
    //   错误消息：${err.message}
    //   错误堆栈：${err.stack}
    //   错误时间：${new Date()}`;
    // fs.appendFile("./err_log.txt", err_log, err => {
    //   res.writeHead(500, {});
    //   res.end("500, 服务器繁忙，请稍后重试");
    // });
    res.writeHead(500, {});
    res.end("500, 服务器繁忙，请稍后重试");
});

module.exports = router;